package com.heima.comment.service.impl;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.api.IWemediaClient;
import com.heima.api.auth.IAuthClient;
import com.heima.comment.pojo.ArticleComment;
import com.heima.comment.pojo.ReplyComment;
import com.heima.comment.service.ICommentService;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.QueryCommentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.common.UserIdThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Xanny
 * @Data 2024/8/22 20:37
 * @Version 1.0
 */
@Service
@Slf4j
public class CommentServiceService implements ICommentService {
    public static final int NORMAL = 0;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IAuthClient authClient;

    @Autowired
    private IWemediaClient wemediaClient;

    @Override
    public ResponseResult saveComment(CommentDto dto) {
        //处理敏感词
        Boolean flag =  handleSensitive(dto.getContent());
        if (!flag) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAILED_SENSITIVE);
        }

        ArticleComment articleComment = new ArticleComment();
        articleComment.setContent(dto.getContent());
        articleComment.setEntryId(dto.getArticleId());
        articleComment.setArticleId(dto.getArticleId());
        articleComment.setAuthorId(Long.valueOf(UserIdThreadLocal.getUserId()));

        //调用user微服务 查询当前用户姓名
        String name = authClient.getById(Long.valueOf(UserIdThreadLocal.getUserId()));
        articleComment.setAuthorName(name);
        articleComment.setImage("http://47.109.179.120:9000/leadnews/2024/08/15/8243853a-2b6e-446a-9d63-3cc6e29e1334.jpg");
        articleComment.setPublishTime(new Date());
        articleComment.setCreatedTime(LocalDateTime.now());
        articleComment.setLikes(NORMAL);
        articleComment.setReply(NORMAL);
        articleComment.setFlag(NORMAL);

        mongoTemplate.save(articleComment);

        return ResponseResult.okResult(null);
    }

    private Boolean handleSensitive(String content) {
        boolean flag = true;
        //查询所有敏感词
        List<WmSensitive> wmSensitives = wemediaClient.listAll();
        if(CollectionUtils.isEmpty(wmSensitives)){
            log.info("未定义敏感词，不做审核");
            return flag;
        }
        List<String> sensitiveWords = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveWords);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if(!CollectionUtils.isEmpty(resultMap)){
            flag = false;
        }

        return flag;
    }

    @Override
    public ResponseResult loadComments(QueryCommentDto dto) {
        Criteria criteria = new Criteria();
        if(dto.getIndex() ==1){
            criteria = Criteria.where("articleId").is(dto.getArticleId())
                    .and("publishTime").lt(dto.getMinDate());
        }else if(dto.getIndex() ==2){
            criteria = Criteria.where("articleId").is(dto.getArticleId())
                    .and("publishTime").gt(dto.getMinDate());
        }

        Query query =Query.query(criteria)
                .with(Sort.by(Sort.Direction.DESC, "publishTime"));

        List<ArticleComment> articleCommentList = mongoTemplate.find(query, ArticleComment.class);

        return ResponseResult.okResult(articleCommentList);
    }

    /**
     * 点赞Version1
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComment(CommentDto dto) {
        //如果用户执行点赞操作 则完成以下业务逻辑
        if (dto.getOperation() == 0){
            //1.先判断该篇文章是否有点赞记录
            List<ReplyComment> replyComments = mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId())), ReplyComment.class);
            if (ObjectUtils.isEmpty(replyComments)){
                //1.1没有的话 新增记录
                ReplyComment replyComment = new ReplyComment();
                replyComment.setCommentId(dto.getCommentId());
                replyComment.setLikes(1);
                mongoTemplate.save(replyComment);
            }else{
                //1.2有的话 更新该评论的点赞数量
                Query userCommentQuery = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
                Update userCommentUpdate = new Update();
                userCommentUpdate.inc("likes",1);
                mongoTemplate.updateFirst(userCommentQuery, userCommentUpdate, ReplyComment.class);
            }
        }else if(dto.getOperation() == 1){
            //1.3取消点赞 该评论的点赞数量-1
            Query userCommentQuery = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
            Update userCommentUpdate = new Update();
            userCommentUpdate.inc("likes",-1);
            mongoTemplate.updateFirst(userCommentQuery, userCommentUpdate, ReplyComment.class);
        }
        //2.更新该用户的的点赞状态
        Query query =Query.query(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        update.set("operation",dto.getOperation());
        mongoTemplate.updateFirst(query, update, ArticleComment.class);
        //3.查询点赞数并返回
        ReplyComment one = mongoTemplate.findOne(Query.query(Criteria.where("commentId").is(dto.getCommentId())), ReplyComment.class);

        Map<String,Integer> data = new HashMap();
        data.put("likes",one.getLikes());
        return ResponseResult.okResult(data);
    }


    /**
     * 点赞Version2.0
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComment_v2(CommentDto dto) {
        if (dto.getOperation() == 0){
            //1.1点赞 更新该评论的点赞数量
            Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",1);
            mongoTemplate.updateFirst(query, update, ArticleComment.class);
        }else{
            //1.2取消点赞 更新该评论的点赞数量
            Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateFirst(query, update, ArticleComment.class);
        }

        //2.更新该用户的的点赞状态
        Query query =Query.query(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        update.set("operation",dto.getOperation());
        mongoTemplate.updateFirst(query, update, ArticleComment.class);

        //3.查询点赞数并返回
        ArticleComment one = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ArticleComment.class);

        Map<String,Integer> data = new HashMap();
        data.put("likes",one.getLikes());
        return ResponseResult.okResult(data);
    }


}
